package com.alimama.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alimama.sms.ResultMsg;
import com.alimama.sms.SmsClient;
import com.alimama.sms.SmsReq;
import com.alimama.sms.SmsType;

/**
 * 短信发送工具类
 * @author 黄标
 *
 */
public class SmsUtils {
	
	private static final String custCode = "860360";							 //[必填] 用户账号
	
	private static final String password = "M1NLLTTE3N";						 //[必填] 账号密码
	
	private static final String serviceBaseUrl = "http://123.58.255.70:8860"; 			 //[必填] https://ip:port

	static Logger log = LoggerFactory.getLogger(SmsUtils.class);
	
	public static boolean sendSms(String content,String custMbl,SmsType smsType) {
	
		SmsReq smsReq = new SmsReq();
		smsReq.setUid(smsType.getUid());							//[选填] 业务标识，由贵司自定义32为数字透传至我司
		smsReq.setCust_code(custCode);				//[必填] 用户账号
		smsReq.setContent(content);				//[必填] 短信内容
		smsReq.setDestMobiles(custMbl);		//[必填] 接收号码，同时发送给多个号码时,号码之间用英文半角逗号分隔(,)
		smsReq.setNeed_report("yes");				//[选填] 状态报告需求与否，是 yes 否 no 默认yes
		smsReq.setSp_code("");						//[选填] 长号码
		smsReq.setMsgFmt("8");						//[选填] 信息格式，0：ASCII串；3：短信写卡操作；4：二进制信息；8：UCS2编码；默认8

		SmsClient smsClient = new SmsClient();
		ResultMsg resultMsg = smsClient.sendSms(smsReq, password, serviceBaseUrl);
		log.info("sendSms.info---custMbl:{},content:{},reponse:{}",custMbl,content,resultMsg.toString());
		if (!resultMsg.isSuccess()) {
			return false;
		} 
		if(!StringUtils.verifyNull(resultMsg.getCode())&& !"0".equals(resultMsg.getCode())){
			return false;
		}
		
		String data = resultMsg.getData();
		try {
			if(!StringUtils.verifyNull(data)){
				JSONObject json = JSONObject.parseObject(data);
				if(!"0".equals(json.get("respCode"))){
					return false;
				}
			}
		} catch (Exception e) {
			log.info("sendSms.info---custMbl:{},json.parse.err:",custMbl,e);
			return false;
		}
	
		return true;
	}
	
	
	public static void main(String[] args) {
		sendSms("您好，您的验证码为245669", "18664300934", SmsType.FORGET_SMS);
	}
	
	//生成随机6位验证码
	public static String getSmsCode(){
		return String.valueOf((int)((Math.random()*9+1)*100000));
	}
	
	public static String getKey(SmsType type,String custMbl,String keyType){
		String key = keyType+"-"+"SmsType"+"-"+type.getUid()+"-"+custMbl;
		log.info("custMbl={},smskey={}",custMbl,key);
		return  key;
	}
}
